import { Toast, Uploader } from 'react-vant'
import Axios, { AxiosRequestConfig } from 'axios'
import config from '../GlobalConfig'
import { aesDecrypt, aesEncrypt } from './encryption'



function errMsg(msg: any) {
  Toast.fail(msg)
}

// 全局配置
Axios.defaults.baseURL = config.baseUrl
Axios.defaults.timeout = config.timeOut



// 请求拦截器

Axios.interceptors.request.use((config: AxiosRequestConfig) => {
  const token = localStorage.getItem('token')
  if (token) {
    Axios.defaults.headers.common['Authorization'] = 'Bearer' + token
  }
  return config
})

const _req = {
  
  post(param: any) {
    
    return new Promise((resolve, reject) => {
      // 创建Axios实例
      let $axios

      // token
      let token = localStorage.getItem('token')
      if (token) {
        token = 'Bearer ' + token
      }

      const config = {
        headers: {
          Authorization: token,
        },
      }
      const data = {
        source: 'web',
        version: 'v1',
        module: param.module,
        interface: param.interface,
        //timestamp: 1628912634,
        timestamp: Math.round(new Date().getTime() / 1000),
      }
      $axios = Axios.post(
        param.url || '/portal',
        aesEncrypt(data, param.data, param.enc),
        config
      )

      if ($axios) {
        
        $axios
          .then((response) => {
            let dataAxios = aesDecrypt(response.data, param.enc)
            const { code } = dataAxios
            if (!code) {
              // 成功
              resolve(dataAxios.data || dataAxios)
            } else {
              switch (code) {
                case 4700:
                  errMsg(dataAxios.message)
                  return
                case 4500:
                  
                  window.location.hash = '/text'
                 
                  return
              }
            }
          })
          .catch((err) => {
            if (!err.response) {
              // 没有返回值，表示是请求失败
              console.error(
                'error -> 网络请求失败，请检查请求地址或请求参数信息'
              )
              reject(err)
            } else if (err.response.statue !== 200) {
              // 有返回值，且请求失败
              let message
              switch (err.response.status) {
                case 400:
                  message = '请求错误'
                  break
                case 401:
                  message = '未授权，请登录'
                  break
                case 403:
                  message = '拒绝访问'
                  break
                case 404:
                  message = `请求地址出错: ${err.response.config.url}`
                  break
                case 408:
                  message = '请求超时'
                  break
                case 500:
                  message = '服务器内部错误'
                  break
                case 501:
                  message = '服务未实现'
                  break
                case 502:
                  message = '网关错误'
                  break
                case 503:
                  message = '服务不可用'
                  break
                case 504:
                  message = '网关超时'
                  break
                case 505:
                  message = 'HTTP版本不受支持'
                  break
                case 'ECONNABORTED':
                  message = '请求超时'
                  break
                default:
                  message = '意外错误'
                  break
              }
              console.error('error ->', message)
              err.message = message
              reject(err)
            } else {
              // 有返回值，请求成功，但接口返回失败
              reject(err)
            }
          })
      }
    })
  },
  // 上传图片
  async upload(file: File, update: Function) {
    const token = localStorage.getItem('token')
    if (token) {
      Axios.defaults.headers.common['Authorization'] = 'Bearer ' + token
    }

    const body = new FormData()
    body.append('file', file)

    const resp = await Axios.post(config.baseUrl + 'upload', body)
    update(resp.data.data.file)
    return { url: resp.data.data.file }
  },
}

export default _req
